package com.farm.view.convertor.impl;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import com.farm.view.convertor.FileConvertorInter;
import com.farm.view.model.ViewFileModelInter;
import com.farm.view.model.utils.CompressFile;
import com.farm.view.model.utils.WdapTxtFileUtils;
import com.farm.view.task.domain.ConvertTaskFile;

/**
 * 压缩文件转换为txt文件进行预览
 * 
 * @author macpl
 *
 */
public class ZipRarToTxtConvertor implements FileConvertorInter {

	@Override
	public String getKey() {
		return "ZIPRAR_TO_TXT";
	}

	@Override
	public String getTitle() {
		return "压缩文件转TXT文件";
	}

	@Override
	public String getNote() {
		return "获得压缩文件的文件列表，记录在txt文件中";
	}

	@Override
	public void doConvert(ConvertTaskFile fileInfo, ViewFileModelInter oviewFileModel,
			ViewFileModelInter tviewFileModel) {
		List<Map<String, String>> files = deCompress(fileInfo.getFile(), fileInfo.getExname());
		File modelFile = tviewFileModel.getModelFile(fileInfo.getFile(), fileInfo.getExname());
		List<String> lines = new ArrayList<>();
		for (Map<String, String> node : files) {
			lines.add(node.get("NAME"));
		}
		Collections.sort(lines, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}
		});
		try {
			WdapTxtFileUtils.WriteTxt(modelFile, lines);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 解压缩
	 */
	private static List<Map<String, String>> deCompress(File file, String filetype) {
		List<Map<String, String>> files = null;
		if (filetype.toLowerCase().equals("zip")) {
			files = CompressFile.getZipFiles(file);
		} else if (filetype.toLowerCase().equals("rar")) {
			files = CompressFile.getRarFiles(file);
		} else {
			throw new RuntimeException("只支持zip和rar格式的压缩包！");
		}
		return files;
	}
}
